﻿using System;
using System.IO;
using System.Data;

namespace Dal
{
    class Credentials
    {
        private static string PATCH;

        static Credentials()
        {
            PATCH = System.Reflection.Assembly.GetExecutingAssembly().Location;
            FileInfo fileInfo = new FileInfo(PATCH);
            PATCH = fileInfo.DirectoryName;
        }

        public static string getCredentias(string ambient)
        {
            DataTable dt = new DataTable("environment");
            dt.Columns.Add("name", typeof(string));
            dt.Columns.Add("location", typeof(string));
            dt.Columns.Add("catalog", typeof(string));
            dt.Columns.Add("user", typeof(string));
            dt.Columns.Add("password", typeof(string));

            DataSet ds = XmlToDataSet("Credentials.xml", ref dt);
            if (ds == null) return null; 

            DataRow[] drs = dt.Select("name = '" + ambient + "'");
            dt = dt.Clone();
            foreach (DataRow dr in drs)
            {
                dt.ImportRow(dr);
            }
            if (dt.Rows.Count > 0)
            {
                if (dt.Rows[0]["name"] == null ||
                   dt.Rows[0]["location"] == null ||
                   dt.Rows[0]["catalog"] == null ||
                   dt.Rows[0]["user"] == null ||
                   dt.Rows[0]["password"] == null)
                {
                    writeLogFile("Incomplete environment information in Credentials.xml file");
                    return null;
                }
                else
                {
                    string connection = string.Empty;
                    connection += "Data Source=" + dt.Rows[0]["location"];
                    connection += ";Initial Catalog=" + dt.Rows[0]["catalog"];
                    connection += ";User ID=" + dt.Rows[0]["user"];
                    connection += ";Password=" + dt.Rows[0]["password"];
                    return connection;
                }
            }
            else
            {
                writeLogFile("No data for \"" + ambient + "\" enviorement");
                return null;
            }
        }

        public static void writeLogFile(string message)
        {
            string log = string.Empty;
            log += PATCH + "\\logs\\Log_" + DateTime.Now.ToString("yyyyMMddHHmmssff") + ".txt";
            try
            {
                if (File.Exists(log))
                {
                    StreamWriter sw = File.AppendText(log);
                    sw.WriteLine("\r\n" + message);
                    sw.Close();
                }
                else
                {
                    System.IO.File.WriteAllText(log, message, System.Text.Encoding.UTF8);
                }
            }
            catch (Exception ex)
            {
                string sSource;
                string sLog;
                string sEvent;

                sSource = "DMS Tools WCF Service";
                sLog = "Application";
                sEvent = "Error trying to write log file: " + ex.Message;

                if (!System.Diagnostics.EventLog.SourceExists(sSource))
                {
                    System.Diagnostics.EventLog.CreateEventSource(sSource, sLog);
                }
                System.Diagnostics.EventLog.WriteEntry(sSource, sEvent, System.Diagnostics.EventLogEntryType.Error);
            }
        }

        public static DataSet XmlToDataSet(string fileName, ref DataTable dt)
        {
            string file = string.Empty;
            try
            {
                StreamReader sr = File.OpenText(PATCH + "\\" + fileName);
                string input = null;
                while ((input = sr.ReadLine()) != null)
                {
                    file += input.Trim();
                }
                sr.Close();
            }
            catch (Exception ex)
            {
                writeLogFile(ex.Message);
                return null;
            }

            DataSet ds = new DataSet();
            ds.Tables.Add(dt);

            try
            {
                StringReader xmlSR = new StringReader(file);
                ds.ReadXml(xmlSR, XmlReadMode.ReadSchema);
                xmlSR.Close();
            }
            catch (Exception ex)
            {
                writeLogFile(ex.Message);
                return null;
            }
            return ds;
        }
    }
}